/**
 * @author lvzhiyi
 *
 * @description 手风琴
 */
import React, { Component } from 'react';
import Panel from './Panel.jsx';
import './style.less';

interface AccordionProps {
    accordion: boolean;
    headClickHandle?: Function;
    defaultKey?: number;
}

interface AccordionState {
    show?: any;
}

class Accordion extends Component<AccordionProps, AccordionState> {
    constructor(props) {
        super(props);
        this.state = {
            show: []
        };
    }
    static Panel = Panel;
    static defaultProps = {
        onChange: () => {},
        accordion: false
    };

    componentDidMount() {
        const { defaultKey } = this.props;
        const { show } = this.state;
        if ('defaultKey' in this.props) {
            show[defaultKey] = true;
            this.setState({ show });
        }
    }

    headClickHandle(activeShow, index, accordion) {
        const { show } = this.state;
        if (accordion) {
            show.forEach((item, i) => {
                show[i] = false;
            });
        }
        show[index] = !activeShow;
        this.setState({ show });
        this.props.onChange(index, !activeShow);
    }

    render() {
        const this_ = this;
        const { children, accordion } = this.props;
        let newChildren = [];
        React.Children.forEach(children, function(child, index) {
            let props = {
                key: index,
                head: child.props.head,
                show: this_.state.show[index] || false,
                headClickHandle(status) {
                    this_.headClickHandle(status, index, accordion);
                }
            };
            newChildren.push(React.cloneElement(child, props));
        });
        return React.createElement('div', null, newChildren);
    }
}
export default Accordion;
